/**
 * @app 钉钉机器人 这里是简介
 * @icon 这里是图标
 * @type action 执行器
 * @author mradxz
 * @id cc.d4w.dingding
 * @version 1.0
 */
var CryptoJS = require("crypto-js")
$ = {
    account: {
        webhook: "https://oapi.dingtalk.com/robot/send?access_token=16445244c4be307c944043290d25d9c99ae0199517d1b3b356a20cd62c0acfec",
        secret: "SEC09f093c5de10882178594bcf3c92a7c29bc05e1927ddd43a6210986c0bf0018b",
    }
}

function sign(secret, timestamp) {
    const stringToSign = timestamp + '\n' + secret;
    const signature = CryptoJS.HmacSHA256(stringToSign, secret).toString(CryptoJS.enc.Base64);
    return signature;
}

function getUrl() {
    const timestamp = Date.now();
    const signature = encodeURIComponent(sign($.account.secret, timestamp));
    const url = $.account.webhook;
    var requestUrl = `${url}&timestamp=${timestamp}&sign=${signature}`;
    return requestUrl;
}
/**
 * @function setAccount 设置账号
 * @param {string} webhook Webhook地址
 * @param {string} secret 秘钥
 */
function setAccount(webhook, secret) {
    $.account = {
        webhook: webhook,
        secret: secret,
    }
}
/**
 * @function test 账号测试
 */
function test() {
    var data = sendText("账号测试")
    if (data.errmsg == "ok") {
        return true;
    }
    return false;
}
/**
 * @function sendText 发送文本消息
 * @param {string} content 文本消息 - 请输入文本消息
 */
function sendText(content) {
    var result = {};
    http.request({
        method: "POST",
        url: getUrl(),
        header: {
            "content-type": "application/json",
        },
        data: {
            "msgtype": "text",
            "text": {
                "content": content
            }
        },
        fail(error) {
            console.error("error", error.errMsg)
        },
        success(res) {
            result = res.data;
        },
    })
    return result;
}
module.exports = {
    nihao: 9999,
    init: function(ee, dd) {
        console.error("钉钉机器人初始化成功 => ", ee, this.nihao)
    },
    sendMessage: function(obj) {
        console.error("钉钉消息发送成功 => ", obj.fuck)
        return true;
    }
}